package cn.pconline.officialclub.web;

import cn.pconline.autoclub.entity.ClubDyna;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaPraise;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.CensorDynaInfoService;
import cn.pconline.autoclub.service.DynaIndexService;
import cn.pconline.autoclub.service.EffectiveDynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.SubjectDynaService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Result;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.CommentDyna;
import cn.pconline.autoclub.util.dyna.CommentDynaUtils;
import cn.pconline.autoclub.web.DynaController;
import cn.pconline.officialclub.entity.OActivity;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OClubDyna;
import cn.pconline.officialclub.entity.OCommonMember;
import cn.pconline.officialclub.entity.OForum;
import cn.pconline.officialclub.service.OActivityService;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.officialclub.service.ODynaService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 官方动态相关
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
@Controller
@RequestMapping("/brand/dyna")
public class ODynaController extends WebKit {

    @Autowired
    private ODynaService oDynaService;
    @Autowired
    private EffectiveDynaService dynaService;
    @Autowired
    private OClubService oClubService;
    @Autowired
    private OActivityService oActivityService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CensorDynaInfoService censorDynaInfoService;
    @Autowired
    private SubjectDynaService subjectDynaService;
    @Autowired
    private DynaIndexService dynaIndexService;
    
    private static final int MAX_TOP_COUNT = 5;
    private static final int DEFAULT_PRAISE_PAGE_SIZE = 13;//动态详细页点赞用户分页大小 获取点赞用户第一页列表,一页最多13个，页面要求

    /**
     * 发表说说，同时同步到民间车友会
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/createCommentDyna", method = RequestMethod.POST)
    @ResponseBody
    public void createCommentDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long oClubId = WebUtils.paramOClubId(request);
        String content = WebUtils.param(request, "content", "");
        int fromType = WebUtils.paramInt(request, "fromType",DynaInfo.FROM_APP);
        JSONArray successImgs = new JSONArray();//成功发表的动态图片
        if (StringUtils.length(content) > DynaController.DEFAULT_MAX_CONTENT_LENGTH) {
            printMsg(response, Result.dataError("非法参数：content的最大长度为" + DynaController.DEFAULT_MAX_CONTENT_LENGTH));
            return;
        }
        JSONArray jsonArray = WebUtils.parseArray(request, "images");
        //不能同时为空
        if (StringUtils.isBlank(content) && (jsonArray == null || jsonArray.isEmpty())) {
            printMsg(response, Result.dataError("内容不能为空！"));
            return;
        }
        OClub oClub = oClubService.findValidClub(oClubId);
        if(oClub == null){
            printMsg(response, Result.dataError("该车友会不存在！"));
            return;
        }
        OCommonMember member = checkMember(request, response);
        if (null == member) {
            return;
        }
        User user = userAuth.getUser(request, response);
        if(oClub.isMustBindPhone() && StringUtils.isBlank(user.getBindPhone())){
            printMsg(response, Result.noPermission("您还没有绑定手机,该车友会只有绑定手机后才能互动,请到个人中心绑定手机号码"));
            return;
        }
        if(oMemberService.isUserLock(user,oClubId)){
            printMsg(response, Result.noPermission("您所绑定的手机号码已经被该车友会封锁,请在个人中心更改绑定的手机号码！"));
            return;
        }
        ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
        // 增加留言
        CommentDyna commentDyna = new CommentDyna();
        commentDyna.setCreateBy(member.getUserId());
        commentDyna.setClubId(clubMember!=null?clubMember.getClubId():0);//同步到民间车友会
        commentDyna.setCreateDate(new Date());
        commentDyna.setCreateName(user.getNickname() != null ? user.getNickname() : user.getUsername());
        commentDyna.setContent(content);
        commentDyna.setUpdateDate(new Date());
        commentDyna.setProvinceId(0);
        commentDyna.setCityId(0);
        commentDyna.setFromType(fromType);
        // 增加留言图片
        List<DynaImage> dynaImages = new ArrayList<DynaImage>();
        // 最多只可以上传9张图片
        if (jsonArray != null) {
            if (jsonArray.size() > DynaController.DEFAULT_MAX_IMAGE_SIZE) {
                printMsg(response, Result.dataError("发表动态最多可以上传" + DynaController.DEFAULT_MAX_IMAGE_SIZE
                        + "张图片!"));
                return;
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject o = JSONObject.parseObject(jsonArray.getString(i));
                DynaImage dynaImage = new DynaImage();
                dynaImage.setSeq(i + 1);// 车友会的图片的seq跟论坛的图片的seq都统一从1开始
                dynaImage.setUrl(o.getString("url"));
                dynaImage.setWidth(o.getIntValue("width"));
                dynaImage.setHeight(o.getIntValue("height"));
                dynaImages.add(dynaImage);
                //（用于首页js刷新）
                JSONObject d = dynaImage.toJSONObject();
                String url;
                if (jsonArray.size() > 1) {
                    url = dynaImage.getUrl120x80();
                } else {
                    url = (dynaImage.getUrl240x160());
                }
                d.put("url", url);
                successImgs.add(d);
            }
        }
        // 图片的URL不可以为空
        for (DynaImage dynaImage : dynaImages) {
            String url = dynaImage.getUrl();
            if (StringUtils.isBlank(url)) {// 注意：这里限制了只有合法的图片才能上传
                printMsg(response, Result.dataError("图片的URL不可以为空!"));
                return;
            }
        }
        //官方车友会
        DynaInfo dynaInfo = oDynaService.createCommentDyna(commentDyna, oClubId, dynaImages);
        String subjectIds = dynaInfo.getSubjectIds();
        // 动态送审
        censorDynaInfoService.notifyCensorSystemCreate(request, commentDyna, dynaInfo.getDynaInfoId(), oClubId);
        //组装成功发表后对象（用于首页js刷新）
        String returnContent= WebUtils.transformToBBSFace(commentDyna.getContent());
        Result rs = Result.instance()
                .set("content", StringUtils.isBlank(subjectIds)?returnContent:WebUtils.dynaSubjectContent(systemConfig.getRoot(), returnContent,subjectIds))
                .set("type", DynaInfo.TYPE_COMMENT)
                .set("templateId", "template-commentDyna")
                .set("avatar", WebUtils.face(commentDyna.getCreateBy(), User.DEFAULT_AVATAR_SIZE))
                .set("nickName", userService.findUser(commentDyna.getCreateBy()).getNickname())
                .set("userId", commentDyna.getCreateBy())
                .set("dynaInfoId", dynaInfo.getDynaInfoId())
                .set("year", DateUtils.format(commentDyna.getCreateDate(), "yyyy"))
                .set("createDate", DateUtils.format(commentDyna.getCreateDate(), "yyyy-MM-dd HH:mm:ss"))
                .set("fmtCreateDate", DateUtils.format(commentDyna.getCreateDate(), "MM-dd HH:mm:ss"))
                .set("praiseCount", 0) //	刚发表点赞数默认为0
                .set("postCount", 0) //  刚发表回复数默认为0
                .set("images", successImgs);
        printMsg(response, Result.success(rs));
    }

    @ResponseBody
    @RequestMapping(value = "/getTopList.do", method = RequestMethod.GET)
    public void getTopList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        int needToViewUrl = WebUtils.paramInt(request, "needToViewUrl", 0);
        int xssEncode = WebUtils.paramInt(request,XSS_ENCODE, XSSENCODECODE);
        long oClubId = WebUtils.paramOClubId(request);
        if (oClubId == 0) {
            printMsg(response, Result.dataError());
            return;
        }
        Pager<DynaInfo> dynaPager = oDynaService.getTopDynaListByClubId(oClubId, MAX_TOP_COUNT);
        dynaService.filterImages(dynaPager);
        JSONArray list = new JSONArray();
        if (dynaPager != null) {
            for (DynaInfo i : dynaPager.getResultList()) {
               String templateId;
                JSONObject obj = new JSONObject();
                 if (needToViewUrl == 1) {
                    obj.put("content",WebUtils.dynaSubjectContent(systemConfig.getRoot(), WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(i.getContent())), i.getSubjectIds() ) );
                } else {
                    obj.put("content", WebUtils.transformToBBSFace(i.getContent()));
                }
                if (i.getType() == DynaInfo.TYPE_ACTIVITY) {
                    OActivity a = oActivityService.findById(OActivity.class, i.getTargetId());
                    if (a == null) {
                        log.error("dirty data,targetId not correct :[dynaInfo:{}],[targetId(activityId):{}]",i.getTargetId());
                        continue;
                    }
                    obj.put("activityId", i.getTargetId());
                    obj.put("activityCover", a.getPicUrl160x120());
                    obj.put("activityTitle", a.getTitle());
                    obj.put("activityStartTime", DateUtils.format(a.getBeginDate()));
                    obj.put("activityEndTime", DateUtils.format(a.getEndDate()));
                    obj.put("activityExpiredTime", DateUtils.format(a.getSignupDate(), "yyyy-MM-dd HH:mm:ss"));
                    obj.put("activityPlace", a.getProvinceId() == 0 ? "线上" : a.getProvinceName() + a.getCityName());
                    obj.put("activityMoney", a.getMoney());
                    obj.put("activityMaxJoin", a.getMaxJoin());
                    templateId = "template-activityDyna";
                } else if (i.getType() == DynaInfo.TYPE_COMMENT) {
                    if(!StringUtils.isBlank(i.getSubjectIds())){
                       templateId = "template-subjectDyna";
                       obj.put("subjectCount",subjectDynaService.countSubjectDyna(i.getSubjectIds()));
                    }else{
                       templateId = "template-commentDyna";
                    }
                } else if (i.getType() == DynaInfo.TYPE_QUESTION || i.getType() == DynaInfo.TYPE_TOPIC) {
                    obj.put("topicId", i.getTargetId());
                    obj.put("forumId", i.getForumId());
                    templateId = "template-topicDyna";
                    obj.put("title", EncodeUtils.encodeForHTML(i.getTitle(), xssEncode));
                    obj.put("content", WebUtils.transformNoBBSFaceThenLimit(i.getContent(), 120, xssEncode));
                    obj.put("isPick", i.getPick());
                    obj.put("petrol", i.getPetrol());
                    obj.put("isRecommend", i.getRecommend());
                } else {
                   continue;
                }
                obj.put("type", i.getType());
                obj.put("templateId", templateId);
                obj.put("avatar", WebUtils.face(i.getCreateBy(), User.DEFAULT_AVATAR_SIZE));
                obj.put("nickName", EncodeUtils.encodeForHTML(userService.findUser(i.getCreateBy()).getNickname(), xssEncode));
                obj.put("userId", i.getCreateBy());
                obj.put("dynaInfoId", i.getDynaInfoId());
                obj.put("year", DateUtils.format(i.getCreateDate(), "yyyy"));
                obj.put("createDate", DateUtils.format(i.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                obj.put("fmtCreateDate", DateUtils.format(i.getCreateDate(), "MM-dd HH:mm:ss"));
                obj.put("praiseCount", i.getPraiseCount());
                obj.put("postCount", i.getPostCount());
                JSONArray array = new JSONArray();
                for (DynaImage img : i.getImages()) {
                    JSONObject o = img.toJSONObject();
                    String url;
                    if (i.getImages().size() > 1) {
                        url = img.getUrl120x80();
                    } else {
                        url = (img.getUrl240x160());
                    }
                    o.put("url", url);
                    array.add(o);
                }
                obj.put("images", array);
                list.add(obj);
            }
        }
        printMsg(response, Result.success("list", list));
    }

    /**
     *
     * 动态置顶
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/top.do", method = RequestMethod.POST)
    public void top(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long oClubId = WebUtils.paramOClubId(request);
        if (oClubId == 0 || dynaInfoId == 0) {
            printMsg(response, Result.dataError());
            return;
        }
        //权限判断
        if (!isAdmin(request, response)) {
            return;
        }
        if (oDynaService.getTopCount(oClubId) >= MAX_TOP_COUNT) {
            printMsg(response, Result.dataError("置顶最多只能显示5条，请先删除！"));
            return;
        }
        boolean isSuccess = oDynaService.doTop(dynaInfoId, oClubId);
        if (isSuccess) {
            printMsg(response, Result.success("置顶成功"));
        } else {
            printMsg(response, Result.error("置顶失败"));
        }
    }

    /**
     *
     * 取消置顶
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cancelTop.do", method = RequestMethod.POST)
    public void cancelTop(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long oClubId = WebUtils.paramOClubId(request);
        if (oClubId == 0 || dynaInfoId == 0) {
            printMsg(response, Result.dataError());
            return;
        }
        //权限判断
        if (!isAdmin(request, response)) {
            return;
        }
        boolean isSuccess = oDynaService.cancelTop(dynaInfoId, oClubId);
        if (isSuccess) {
            printMsg(response, Result.success());
        } else {
            printMsg(response, Result.error("删除失败！"));
        }
    }

    /**
     *
     * 会长或副会长删除车友会动态
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDyna.do", method = RequestMethod.POST)
    public void deleteDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long oClubId = WebUtils.paramOClubId(request);
        if (oClubId == 0 || dynaInfoId == 0) {
            printMsg(response, Result.dataError());
            return;
        }
        //权限判断
        if (!isAdmin(request, response)) {
            return;
        }
        User user = userAuth.getUser(request, response);
        OClubDyna clubDyna = oDynaService.findClubDyna(dynaInfoId, oClubId);
        //官方
        oDynaService.deleteClubDyna(oClubId, dynaInfoId);
        //民间车友会
        ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
        if (clubMember != null) {
            dynaService.deleteClubDyna(clubMember.getClubId(), dynaInfoId);
        }
        printMsg(response, Result.success());
    }

    /**
     *
     * 删除车友会动态
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/deleteUserDyna.do", method = RequestMethod.POST)
    public void deleteUserDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long oClubId = WebUtils.paramOClubId(request);
        if (oClubId == 0 || dynaInfoId == 0) {
            printMsg(response, Result.dataError());
            return;
        }
        User user = checkUser(request, response);
        if (user == null) {
            return;
        }
        OClubDyna clubDyna = oDynaService.findClubDyna(dynaInfoId, oClubId);
        if (clubDyna == null) {
            printMsg(response, Result.dataError("动态不存在"));
            return;
        }
        if (clubDyna.getCreateBy() != user.getUid()) {
            printMsg(response, Result.noPermission("只有创建者自己才可以删除"));
            return;
        }
        oDynaService.deleteClubDyna(oClubId, dynaInfoId);//同时删除车友会动态
        //民间车友会
        ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
        if (clubMember != null) {
            dynaService.deleteClubDyna(clubMember.getClubId(), dynaInfoId);
        }
        printMsg(response, Result.success());
    }

    /**
     * 帖子列表页
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/list.do", method = RequestMethod.GET)
    public String list(HttpServletRequest request, HttpServletResponse response) {
        long oClubId = WebUtils.paramOClubId(request);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            return redirect404(response);
        }
        int order = WebUtils.paramInt(request, "order", 0);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        User user = userAuth.getUser(request, response);
        boolean isOwner = false;
        boolean isClubUser = false;
        if (user != null && user.getUid()>0) {
            OCommonMember clubMember = oMemberService.findCommonMember(user.getUid(), oClubId);
            if (clubMember != null && clubMember.getOClubId() > 0) {
                isClubUser = true;
            }
            if (clubMember != null && clubMember.isAdmin()) {
                isOwner = true;
            }
        }
        long forumId = oClub.getForumId();
        if (forumId > 0) {
            OForum clubForum = oClubService.findForum(forumId);
            request.setAttribute("clubForum", clubForum);
        }

        Pager<DynaInfo> pager = oDynaService.getTopicDynaListByClubId(oClubId, pageNo, DEF_PAGE_SIZE, order);
        //过滤掉不合法的图片
        pager = dynaService.filterImages(pager);
        if (pager == null) {
            pager = Pager.buildEmptyPager();
        }
        request.setAttribute("isUserLock", oMemberService.isUserLock(user, oClubId));
        request.setAttribute("pager", pager);
        request.setAttribute("order", order);
        request.setAttribute("isOwner", isOwner);
        request.setAttribute("isClubUser", isClubUser);
        request.setAttribute("oClub", oClub);
        request.setAttribute("user", user);
        return getPcTemplPath("/dyna/list");
    }

    /**
     * 帖子精华列表页
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/listPick.do", method = RequestMethod.GET)
    public String listPick(HttpServletRequest request, HttpServletResponse response) {
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEF_PAGE_SIZE, DEF_MIN_PAGESIZE, DEF_MAX_PAGESIZE);
        long oClubId = WebUtils.paramOClubId(request);
        int order = WebUtils.paramInt(request, "order", 0);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null || pageNo < 1) {
            return redirect404(response);
        }
        User user = userAuth.getUser(request, response);
        long forumId = oClub.getForumId();
        if (forumId > 0) {
            OForum clubForum = oClubService.findForum(forumId);
            request.setAttribute("clubForum", clubForum);
        }
        Pager<DynaInfo> pager = oDynaService.getPickTopicDynaListByClubId(oClubId, pageNo, pageSize, order);
        //过滤掉不合法的图片
        pager = dynaService.filterImages(pager);
        if (pager == null) {
            pager = Pager.buildEmptyPager();
        }
        if (!checkPageMaxNo(request, response, pageNo, pager.getPageCount())) {
            return null;
        }
        if(user!=null && user.getUid()>0){
            OCommonMember member = oMemberService.findCommonMember(user.getUid(), oClubId);
            request.setAttribute("isClubUser", member != null);
        }
        request.setAttribute("isUserLock", oMemberService.isUserLock(user, oClubId));
        request.setAttribute("order", order);
        request.setAttribute("oClubId", oClubId);
        request.setAttribute("pager", pager);
        request.setAttribute("user", user);
        request.setAttribute("oClub", oClub);
        return getPcTemplPath("/dyna/pickList");
    }

    /**
     * 获取单条动态详情 请求参数：dynaInfoId clubId
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/dynaDetail", method = RequestMethod.GET)
    public String dynaDetail(HttpServletRequest request, HttpServletResponse response) {
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEF_PAGE_SIZE, DEF_MIN_PAGESIZE, DEF_MAX_PAGESIZE);
        long oClubId = WebUtils.paramOClubId(request);

        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            return redirect404(response);
        }
        if (pageNo < 1 || 0 == oClubId || dynaInfoId == 0) {
            return redirect404(response);
        }
        OClubDyna clubDyna = oDynaService.findClubDyna(dynaInfoId, oClubId);
        //判断动态是否存在、是否为帖子（包含提问）、是否为删除动态
        if (clubDyna == null || DynaInfo.isTopic(clubDyna.getType())
                || clubDyna.getStatus() == DynaInfo.STATUS_DELETE) {
            //帖子动态没有详情页
            return redirect404(response);
        }
        //动态
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, clubDyna.getCreateDate());
        if (dynaInfo == null) {
            log.error("车友会动态索引表有脏数据[clubId,dynaInfoId][{},{}]，对应的动态不存在", oClubId, dynaInfoId);
            return redirect404(response);
        }
        //回复列表
        Pager<DynaReply> pager = dynaService.getReplyListByDynaInfoId(dynaInfoId, pageNo, pageSize);
        if (!checkPageMaxNo(request, response, pageNo, pager.getPageCount())) {
            return null;
        }

        dynaService.filterImages(dynaInfo);//过滤掉不合法的图片
        String content = dynaInfo.getContent();
        if (dynaInfo.getType() == DynaInfo.TYPE_ACTIVITY) {
            OActivity a = oActivityService.findById(OActivity.class, dynaInfo.getTargetId());
            if (a == null) {
                log.error("dirty data,targetId not correct :[dynaInfo:{}],[oClubId:{}],[targetId(activityId):{}]", dynaInfo.getDynaInfoId(), oClubId, dynaInfo.getTargetId());
                return redirect404(response);
            }
            content = a.getTitle();//活动动态的content没存
            request.setAttribute("activity", a);
        }
        dynaInfo.setCreateName(userService.findUser(dynaInfo.getCreateBy()).getNickname());
        request.setAttribute("oClub", oClub);
        request.setAttribute("dynaInfo", dynaInfo);
        request.setAttribute("content", content);
        //用户相关
        User user = userAuth.getUser(request, response);
        boolean isClubAdmin = false;
        boolean isPresident = false;
        boolean isMember = false;
        boolean isLogin = false;
        if (user.getUid() > 0) {
            isLogin = true;
            OCommonMember member = oMemberService.findCommonMember(user.getUid(), oClubId);
            if (member != null) {
                isMember = true;
                isClubAdmin = member.isAdmin();
                isPresident = member.getAdminType() == OCommonMember.ADMIN_TYPE_PRESIDENT;
            }
        }
        request.setAttribute("user", user);
        request.setAttribute("isMember", isMember);
        request.setAttribute("isLogin", isLogin);
        request.setAttribute("isPresident", isPresident);
        request.setAttribute("isClubAdmin", isClubAdmin);
        request.setAttribute("pager", pager);
        Pager<User> praisePager = dynaService.getPraiseUserList(dynaInfoId, 1, DEFAULT_PRAISE_PAGE_SIZE);
        request.setAttribute("praisePager", praisePager);
        int praseCount = dynaService.getPraseCountByUid(dynaInfoId, user.getUid());
        if (praseCount == 1) {
            request.setAttribute("isPraise", true);
        } else {
            request.setAttribute("isPraise", false);
        }
        //seo要求
        String dynaDescForTitle = StringUtil.byteSubstring(content, 30, null);
        String dynaDescForDesc = StringUtil.simpleStringFilter(content, "img");//过滤图片
        dynaDescForDesc = dynaDescForDesc.replaceAll("\\[em([0-9]*)\\]", "[图]");//过滤表情
        dynaDescForDesc = StringUtil.byteSubstring(dynaDescForDesc, 112, "。。。。。。");//截取前100个汉字+6个省略号
        request.setAttribute("dynaDescForTitle", dynaDescForTitle);
        request.setAttribute("dynaDescForDesc", dynaDescForDesc);
        return getPcTemplPath("/dyna/detail");
    }

    @ResponseBody
    @RequestMapping(value = "/getDynaListByClubId.do", method = RequestMethod.GET)
    public void getDynaListByClubId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", 10, 5, 20);
        long oClubId = WebUtils.paramOClubId(request);
        int xssEncode = WebUtils.paramInt(request, "xssEncode", 2);
        int needToViewUrl = WebUtils.paramInt(request, "needToViewUrl", 0);
        Pager<DynaInfo> dynaPager = oDynaService.getDynaListByClubId(oClubId,null,false,pageNo, pageSize, ODynaService.ORDER_CREATE_DATE);
        dynaService.filterImages(dynaPager);
        JSONArray list = new JSONArray();
        if (dynaPager != null) {
            for (DynaInfo i : dynaPager.getResultList()) {
               String templateId;
                JSONObject obj = new JSONObject();
                 if (needToViewUrl == 1) {
                    obj.put("content",WebUtils.dynaSubjectContent(systemConfig.getRoot(), WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(i.getContent())), i.getSubjectIds() ) );
                } else {
                    obj.put("content", WebUtils.transformToBBSFace(i.getContent()));
                }
                if (i.getType() == DynaInfo.TYPE_ACTIVITY) {
                    OActivity a = oActivityService.findById(OActivity.class, i.getTargetId());
                    if (a == null) {
                        log.error("dirty data,targetId not correct :[dynaInfo:{}],[targetId(activityId):{}]",i.getTargetId());
                        continue;
                    }
                    obj.put("activityId", i.getTargetId());
                    obj.put("activityCover", a.getPicUrl160x120());
                    obj.put("activityTitle", a.getTitle());
                    obj.put("activityStartTime", DateUtils.format(a.getBeginDate()));
                    obj.put("activityEndTime", DateUtils.format(a.getEndDate()));
                    obj.put("activityExpiredTime", DateUtils.format(a.getSignupDate(), "yyyy-MM-dd HH:mm:ss"));
                    obj.put("activityPlace", a.getProvinceId() == 0 ? "线上" : a.getProvinceName() + a.getCityName());
                    obj.put("activityMoney", a.getMoney());
                    obj.put("activityMaxJoin", a.getMaxJoin());
                    templateId = "template-activityDyna";
                } else if (i.getType() == DynaInfo.TYPE_COMMENT) {
                    if(!StringUtils.isBlank(i.getSubjectIds())){
                       templateId = "template-subjectDyna";
                       obj.put("subjectCount",subjectDynaService.countSubjectDyna(i.getSubjectIds()));
                    }else{
                       templateId = "template-commentDyna";
                    }
                } else if (i.getType() == DynaInfo.TYPE_QUESTION || i.getType() == DynaInfo.TYPE_TOPIC) {
                    obj.put("topicId", i.getTargetId());
                    obj.put("forumId", i.getForumId());
                    templateId = "template-topicDyna";
                    obj.put("title", EncodeUtils.encodeForHTML(i.getTitle(), xssEncode));
                    obj.put("content", WebUtils.transformNoBBSFaceThenLimit(i.getContent(), 120, xssEncode));
                    obj.put("isPick", i.getPick());
                    obj.put("petrol", i.getPetrol());
                    obj.put("isRecommend", i.getRecommend());
                } else {
                   continue;
                }
                obj.put("type", i.getType());
                obj.put("templateId", templateId);
                obj.put("avatar", WebUtils.face(i.getCreateBy(), User.DEFAULT_AVATAR_SIZE));
                obj.put("nickName", EncodeUtils.encodeForHTML(userService.findUser(i.getCreateBy()).getNickname(), xssEncode));
                obj.put("userId", i.getCreateBy());
                obj.put("dynaInfoId", i.getDynaInfoId());
                obj.put("year", DateUtils.format(i.getCreateDate(), "yyyy"));
                obj.put("createDate", DateUtils.format(i.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                obj.put("fmtCreateDate", DateUtils.format(i.getCreateDate(), "MM-dd HH:mm:ss"));
                obj.put("praiseCount", i.getPraiseCount());
                obj.put("postCount", i.getPostCount());
                obj.put("fromType", i.getFromType());
                JSONArray array = new JSONArray();
                for (DynaImage img : i.getImages()) {
                    JSONObject o = img.toJSONObject();
                    String url;
                    if (i.getImages().size() > 1) {
                        url = img.getUrl120x80();
                    } else {
                        url = (img.getUrl240x160());
                    }
                    o.put("url", url);
                    array.add(o);
                }
                obj.put("images", array);
                list.add(obj);
            }
        }
        printMsg(response, Result.success("list", list));
    }

    @ResponseBody
    @RequestMapping(value = "/getPraiseList.do", method = RequestMethod.GET)
    public void getPraiseList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        User user = checkUser(request, response);
        if (user == null) {
            return;
        }
        List<Long> ids = WebUtils.paramLongs(request, "dynaInfoIds");
        JSONArray arr = new JSONArray();
        if (!ids.isEmpty()) {
            List<DynaPraise> list = dynaService.listDynaPraise(user.getUid(), ids);
            for (DynaPraise dp : list) {
                JSONObject o = new JSONObject();
                o.put("dynaInfoId", dp.getDynainfoId());
                arr.add(o);
            }
        }
        printMsg(response, Result.success("list", arr));
    }

    /**
     * 获取单条动态详情的所有图片 请求参数：dynaInfoId 提供给大图展示用的
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getDynaImages.do", method = RequestMethod.GET)
    @ResponseBody
    public void getDynaImages(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long oClubId = WebUtils.paramLong(request, "oClubId", 0);
        if (dynaInfoId == 0 || oClubId == 0) {
            printMsg(response, "[]", callback);
            return;
        }
        OClubDyna oClubDyna = oDynaService.findClubDyna(dynaInfoId, oClubId);
        if (oClubDyna == null || oClubDyna.getStatus() == ClubDyna.STATUS_DELETE) {
            printMsg(response, "[]", callback);
            return;
        }
        DynaInfo info = dynaService.findDynaInfoById(dynaInfoId, oClubDyna.getCreateDate());
        if (info == null) {
            printMsg(response, "[]", callback);
            return;
        }

        info.setImages(dynaService.getImagesByDynaInfoId(dynaInfoId, 0));//查所有图片
        dynaService.filterImages(info);

        JSONArray arr = new JSONArray();
        for (DynaImage image : info.getImages()) {
            arr.add(image.toJSONObject());
        }
        printMsg(response, arr.toJSONString(), callback);
    }
}
